import {_decorator, Component, director, math} from 'cc';
import {Actor} from "db://assets/Script/Actor/Actor";
import {Idle} from "db://assets/Script/Actor/state/Idle";
import {StateEnum} from "db://assets/Script/Enums/StateEnum";
import {Die} from "db://assets/Script/Actor/state/Die";
import {VirtualInput} from "db://assets/Script/Inputs/VirtualInput";
import {Run} from "db://assets/Script/Actor/state/Run";
import {GameEventEnum} from "db://assets/Script/Enums/GameEventEnum";
import {Attack} from "db://assets/Script/Actor/state/Attack";
import {AnimationEnum} from "db://assets/Script/Enums/AnimationEnum";

const {ccclass, property, requireComponent} = _decorator;

@ccclass('PlayerController')
@requireComponent(Actor)
export class PlayerController extends Component {
    actor: Actor | null = null;

    static instance: PlayerController | null = null;

    isAttack: boolean = false

    onLoad() {
        PlayerController.instance = this;

    }

    start() {
        this.actor = this.node.getComponent(Actor)
        this.actor.stateManager.registerState(new Idle(StateEnum.IDLE, this.actor))
        this.actor.stateManager.registerState(new Die(StateEnum.DIE, this.actor))
        this.actor.stateManager.registerState(new Run(StateEnum.RUN, this.actor))
        this.actor.stateManager.registerState(new Attack(StateEnum.ATTACK, this.actor))
        this.actor.stateManager.startStateWith(StateEnum.IDLE)

        director.on(GameEventEnum.OnAttackButtonClicked, this.attack, this)
    }

    update(deltaTime: number) {
        if (this.actor.dead) return

        let horizontal: number = VirtualInput.horizontal;
        let vertical: number = VirtualInput.vertical;
        this.actor.input.set(horizontal, vertical)

        if (this.actor.input.length() > math.EPSILON) {
            //向量长度大于math.EPSILON表示非静止状态
            console.log("切换Run状态")
            this.actor.stateManager.transitionTo(StateEnum.RUN)
        } else {
            console.log("切换Idle状态")
            this.actor.stateManager.transitionTo(StateEnum.IDLE)
        }
    }

    onDestroy() {
        PlayerController.instance = null;
        director.off(GameEventEnum.OnAttackButtonClicked, this.attack, this)
    }


    attack() {
        if (!this.isAttack) {
            this.actor.animation.play(AnimationEnum.PLAYER_ATTACK)
            // this.actor.stateManager.transitionTo(StateEnum.ATTACK)
            this.isAttack = true
        }
    }
}


